package com.ecas.code.generator.util;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtil {
    private static final Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
    private static Map<String, Properties> fileNamePropertiesMap = Maps.newConcurrentMap();

    private PropertiesUtil() {
    }

    public static Properties getProperties(String propertiesFileName) {
        Properties properties = fileNamePropertiesMap.get(propertiesFileName);
        if (properties == null) {
            try {
                loadProperties(propertiesFileName);
                properties = fileNamePropertiesMap.get(propertiesFileName);
            } catch (IOException e) {
                log.error("load properties is error,reason is can't not found file:{}", propertiesFileName);
            }
        }
        return properties;
    }

    public static Object getValue(String propertiesFileName, String key) throws IOException {
        Properties properties = fileNamePropertiesMap.get(propertiesFileName);
        if (properties == null) {
            loadProperties(propertiesFileName);
        } else {
            return properties.get(key);
        }
        return null;

    }

    private static void loadProperties(String propertiesFileName) throws IOException {
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFileName);
        if (inputStream == null) {
            throw new FileNotFoundException("can't find propertiesFile:" + propertiesFileName);
        }
        Properties properties = new Properties();
        properties.load(inputStream);
        fileNamePropertiesMap.put(propertiesFileName, properties);
    }
}
